import * as apis from 'services/graphicMsg'
import * as types from '../mutation-types'

const state = {
  list: [],
  groupList: [],
  total: 0,
  info: {},
}

const actions = {
  async getArticleList({ commit }, payload = {}) {
    const data = await apis.getArticleList(payload)
    commit(types.GET_ARTICLE_LIST_SUCCESS, data)
  },

  async getArticleById({ commit }, id) {
    const data = await apis.getArticleById(id)
    commit(types.GET_ARTICLE_BY_ID_SUCCESS, data)
  },

  async getImgTextGroupList({ commit }) {
    const res = await apis.getImgTextGroupList()
    commit(types.GET_IMG_TEXT_GROUP_LIST_SUCCESS, res.data)
  },

  async imgTextGrouping({ commit }, { id, gid }) {
    commit(types.IMG_TEXT_GROUPING, { id, gid })
    const res = await apis.imgTextGrouping({ id, gid })
    return res
  },
}

const mutations = {
  [types.GET_ARTICLE_LIST_SUCCESS](state, data) {
    state.list = data.data
    state.total = data.total
  },

  [types.GET_ARTICLE_BY_ID_SUCCESS](state, data) {
    state.info = data
  },

  [types.GET_IMG_TEXT_GROUP_LIST_SUCCESS](state, data) {
    const ret = data
    ret.unshift({
      id: 0,
      name: '未分组',
      status: 1,
    })
    state.groupList = ret
  },

  [types.IMG_TEXT_GROUPING](state, { id, gid }) {
    state.list = state.list.map((item) => {
      if (item.id === id) {
        item.gid = gid
      }
      return item
    })
  },
}

export default {
  state,
  actions,
  mutations,
}
